package cn.zniot.so.transport.server;

import cn.zniot.so.application.constant.Constants;
import cn.zniot.so.transport.asynpack.HBPacketD;
import cn.zniot.so.transport.exception.NetException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.executor.ExecutorFilter;
import org.apache.mina.filter.keepalive.KeepAliveMessageFactory;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * BoxServer服务器
 */
public class BoxAndClientServer extends ServerAdapter {
	private static final Log logger = LogFactory.getLog(BoxAndClientServer.class);

	private ThreadPoolExecutor threadPool = null;

	public NioSocketAcceptor acceptor = null;

	private int logicProcessor = 1;

	private int port;

	public BoxAndClientServer(int logicProcessor, int serverPort) {
		this.logicProcessor = logicProcessor;
		this.port = serverPort;
	}

	@Override
	public void init() {
		this.acceptor = new NioSocketAcceptor();
		if (this.factory != null) {
			this.acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(this.factory));
		}
		this.threadPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(this.logicProcessor);
		this.acceptor.getFilterChain().addLast("threadPool", new ExecutorFilter(this.threadPool));
		// this.acceptor.setBacklog(backlog);
		/** 添加心跳过滤器 */
		/*
		 * KeepAliveFilter heartBeatFilter = new KeepAliveFilter(new
		 * KeepAliveMessageFactoryImpl(), IdleStatus.READER_IDLE);
		 * heartBeatFilter.setForwardEvent(false);
		 * heartBeatFilter.setRequestInterval(5);// 发送频率(秒)
		 * heartBeatFilter.setRequestTimeout(60);// 超时
		 * heartBeatFilter.setRequestTimeoutHandler
		 * (KeepAliveRequestTimeoutHandler.DEAF_SPEAKER);
		 * this.acceptor.getFilterChain().addBefore("threadPool", "heartbeat",
		 * heartBeatFilter);
		 */
		if (this.handler != null) {
			this.acceptor.setHandler(this.handler);
		} else {
			this.acceptor.setHandler(this);
		}
		// this.acceptor.getSessionConfig().setReceiveBufferSize(2);//设置输入缓冲区的大小
		// this.acceptor.getSessionConfig().setSendBufferSize(2);//设置输出缓冲区的大小
	}

	@Override
	public void startup() throws NetException {
		try {
			// shutdown();
			this.acceptor.bind(new InetSocketAddress(this.port));
			if (logger.isDebugEnabled()) {
				logger.debug("Box Server is listening on port " + this.port);
			}
		} catch (IOException e) {
			// shutdown();
			throw new NetException("Box服务端口绑定异常:", e);
		}
	}

	@Override
	public void shutdown() throws NetException {
		super.shutdown();
	}

	/**
	 * 内部类，实现心跳工厂
	 */
	private static class KeepAliveMessageFactoryImpl implements KeepAliveMessageFactory {

		public Object getRequest(IoSession session) {
			return HBPacketD.getInstance();
		}

		public Object getResponse(IoSession session, Object request) {
			return null;
		}

		public boolean isRequest(IoSession session, Object message) {
			if (message.equals(Constants.HEART_BEAT_DOWN)) {
				System.out.println("收到一个心跳包..........." + session.toString());
				return true;
			}
			return false;
		}

		public boolean isResponse(IoSession session, Object message) {
			return false;
		}
	}

}
